package com.wbs.common;

import com.wbs.exception.ParamException;
import com.wbs.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
    // 异常处理
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        String url = request.getRequestURL().toString();
        ModelAndView mv;
        String defaultMsg = "SYSTEM ERROR";  // 默认返回的错误

        // 所有的json请求都以.json结尾，所有的页面请求都以.page结尾

        if (url.endsWith(".json")) {
            if (ex instanceof PermissionException || ex instanceof ParamException) {
                JsonData result = JsonData.fail(ex.getMessage());
                // spring-servlet.xml中配置的jsonView，所以下边必须要用jsonView，儿不能用其他的
                mv = new ModelAndView("jsonView", result.toMap());

            } else {
                log.error("unknow json exception" + url, ex);
                JsonData result = JsonData.fail(defaultMsg);
                mv = new ModelAndView("jsonView", result.toMap());

            }
        } else if (url.endsWith(".page")) {
            log.error("unknow page exception" + url, ex);

            JsonData result = JsonData.fail(defaultMsg);  // 这儿用默认的msg
            // exception 会自动去找exception.jsp页面
            mv = new ModelAndView("exception", result.toMap());

        } else {
            log.error("unknow exception" + url, ex);

            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("jsonView", result.toMap());  // 其他返回 JSON 格式数据
        }


        return mv;
    }
}
